package com.sllp.C71S3TsllpShop.web.back;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.alipay.api.internal.util.StringUtils;
import com.sllp.C71S3TsllpShop.bean.BigType;
import com.sllp.C71S3TsllpShop.bean.BigTypeExample;
import com.sllp.C71S3TsllpShop.bean.Business;
import com.sllp.C71S3TsllpShop.bean.Image;
import com.sllp.C71S3TsllpShop.bean.ImageExample;
import com.sllp.C71S3TsllpShop.bean.Product;
import com.sllp.C71S3TsllpShop.bean.ProductExample;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.SmallType;
import com.sllp.C71S3TsllpShop.bean.SmallTypeExample;
import com.sllp.C71S3TsllpShop.bean.Specs;
import com.sllp.C71S3TsllpShop.bean.SpecsExample;
import com.sllp.C71S3TsllpShop.biz.impl.BigTypeBizImpl;
import com.sllp.C71S3TsllpShop.dao.BigTypeMapper;
import com.sllp.C71S3TsllpShop.dao.ImageMapper;
import com.sllp.C71S3TsllpShop.dao.ProductMapper;
import com.sllp.C71S3TsllpShop.dao.SmallTypeMapper;
import com.sllp.C71S3TsllpShop.dao.SpecsMapper;
import com.sun.mail.handlers.image_gif;


@Controller
public class BackProductAddAction {

	@Value("${spring.resources.staticLocations}")
	private String[] uploadDir;
	
	@Resource
	BigTypeMapper btm;
	
	@Resource 
	SmallTypeMapper stm;
	
	@Resource 
	ProductMapper pm;
	
	@Resource
	SpecsMapper sm ;
	
	@Resource
	ImageMapper im;
	
	
	
	@GetMapping("back/toProductAdd.do")
	public String toProductAdd(Model m ) {
		List<BigType> list=new ArrayList<BigType>();
		list=btm.selectByExample(null);
		m.addAttribute("bigtype", list);
		return "back/product-add::productAdd";
	}
	
	@PostMapping("back/findsmallType.do")
	public String findSmalType(int bigType,Model m){
		//根据大类型id获取小类型
		List<SmallType> smalllist =new ArrayList<SmallType>();
		//SmallType smallType =new SmallType();
		SmallTypeExample stb =new SmallTypeExample();
		stb.createCriteria().andParentEqualTo(bigType);
		smalllist=stm.selectByExample(stb);
		m.addAttribute("smalltype", smalllist);
		return "back/product-add::smallTypeSelect";
		
		
	}
	
//	@PostMapping("back/test.do")
//	public void test(HttpServletRequest req,@RequestBody String[] list1) {
//		 
//	            for (int i = 0; i < list1.length; i++) {
//	                String idsss = list1[i];
//	                System.out.println("requestBody获取传递的json数组参数：" + idsss);
//	            }
//		
//	}
//	
	
	@ResponseBody
	@PostMapping("back/addProduct.do")
	public Result testPost(@SessionAttribute(name="backLoginBusiness") Business business,@RequestParam(required=true) String listName,@RequestParam int smallid,@RequestParam List<String> listSpecs,@RequestParam List<String> listNum,
			@RequestParam List<String> listPrice,@RequestParam List<String> listDiscount,@RequestParam  String description ,@RequestParam("file")MultipartFile[]file 	
			) throws IOException {
		Result result =new Result();
		int ok=0;
		System.out.println(description);
		/**
		 * 商品表添加
		 */
		Timestamp nowdate = new Timestamp(System.currentTimeMillis());//获取当前时间
		double discount;
		discount=Double.parseDouble(listDiscount.get(0));
		List<BigDecimal>list =new ArrayList<BigDecimal>();
		for (String string : listPrice) {
			BigDecimal bigDecimal =new BigDecimal(string);
			list.add(bigDecimal);
		}
		Product p =new Product();
		p.setName(listName);
		p.setDiscount(discount);
		p.setShelveTime(nowdate);
		p.setModifyTime(nowdate);
		p.setMarketPrice(Collections.max(list));
		p.setType(smallid);
		p.setBusiness(business.getId());
		p.setDescriptioin(description);
		/**
		 * 购买数量默认为零
		 */
		p.setBuyNum(0);
		/**
		 * 默认状态为1 :未启用
		 */
		p.setState(2);
		ok=pm.insertSelective(p);
		if(ok==0) {
			return new Result(ok,"添加失败");
		}
		
		/**
		 * 小规格表添加
		 */
		Specs sp =new Specs();
		for(int i=0;i<listSpecs.size();i++) {
			BigDecimal bigDecimal2 =new BigDecimal(listPrice.get(i));
			sp.setProduct(p.getId());
			sp.setName(listSpecs.get(i));
			sp.setProductNum(Integer.parseInt(listNum.get(i)));
			sp.setProductPrice(bigDecimal2);
			ok=sm.insertSelective(sp);
		}
		if(ok==0) {
			return new Result(ok,"添加失败");
		}

		/**
		 * 图片表添加
		 */
		String path= uploadDir[0].substring("file:/".length());
		String fileName="";
		System.out.println("path:"+path);
		
		
		//String path =uploadDir[0].substring("file:/".length());
		Image image =new Image();
		for(int i=0;i<file.length;i++) {
			String productFileName=file[i].getOriginalFilename();
			String suffix = productFileName.substring(productFileName.lastIndexOf('.'));
			String addFileName=String.valueOf(System.currentTimeMillis()).substring(6);
			fileName = "business/product/"+addFileName+suffix;
			
			//判断文件类型是否正确
			String contentType = file[i].getContentType();
			String result1="";
			if (contentType.equals("image/pjpeg")
					|| contentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			} else if (contentType.equals("image/png")
					|| contentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
			} else if (contentType.equals("image/jfif")) {
			}else if (contentType.equals("image/gif")) {
			}else if (contentType.equals("image/bmp")) {
			} else {
				return new Result(0, "文件类型错误");
			}
			
			
			File diskFile=new File(path+fileName);
			File diskFile1=new File("../"+fileName);
			if (!diskFile.exists()) { // 如果路径不存在，创建
				diskFile.mkdirs();
			}
			System.out.println("diskFile:"+diskFile);
			file[i].transferTo(diskFile);
			image.setProduct(p.getId());
			image.setUrl(diskFile1.toString());
			//image.setBusiness(business.getId());
			/**
			 * 默认图片状态为 1 未启用
			 */
			image.setState(1);
			ok=im.insertSelective(image);
		}
		if(ok>0) {
			return new Result(ok,"你添加的商品已上传审核");
		}else {
			return new Result(ok,"添加失败");
		}
		
	}
	
	@ResponseBody
	@PostMapping("back/deleteimg.do")
	public Result deleteimg(int id) {
		
		int ok=0;
		ok=im.deleteByPrimaryKey(id);
		if(ok>0) {
			return new Result(ok,"删除图片成功");
		}
		return new Result(ok,"删除图片失败");
	}
	
	
	@ResponseBody
	@PostMapping("back/ModifyProduct.do")
	public Result testModify(@SessionAttribute(name="backLoginBusiness") Business business,@RequestParam(required=true) String listName,@RequestParam int smallid,@RequestParam List<String> listSpecs,@RequestParam List<String> listNum,
			@RequestParam List<String> listPrice,@RequestParam List<String> listDiscount,@RequestParam int id,@RequestParam  String description ,@RequestParam("file")MultipartFile[]file 		
			) throws IOException {
		Result result =new Result();
		int ok=0;
		/**
		 * 商品表修改
		 */
		Timestamp nowdate = new Timestamp(System.currentTimeMillis());//获取当前时间
		double discount;
		discount=Double.parseDouble(listDiscount.get(0));
		List<BigDecimal>list =new ArrayList<BigDecimal>();
		Product p =new Product();
		//System.out.println(list3.get(0).toString()+"==="+list3.size());
		if(listPrice.get(0)!="" ) {
			for (String string : listPrice) {
				BigDecimal bigDecimal =new BigDecimal(string);
				list.add(bigDecimal);
				
			}
			p.setMarketPrice(Collections.max(list));
			p.setDiscount(discount);
		}	
			
			p.setName(listName);
			p.setShelveTime(nowdate);
			p.setType(smallid);
			p.setBusiness(business.getId());
			if(description!="") {
				p.setDescriptioin(description);
			}
			
			/**
			 * 默认状态为2 :已启用
			 */
			p.setState(2);
		ProductExample pe =new ProductExample();
		pe.createCriteria().andBusinessEqualTo(business.getId()).andIdEqualTo(id);
		ok=pm.updateByExampleSelective(p, pe);
		if(ok==0) {
			return new Result(ok,"修改失败1");
		}
		
		/**
		 * 小规格表修改
		 */
		Specs sp =new Specs();
		SpecsExample se1 =new SpecsExample();
		se1.createCriteria().andProductEqualTo(id);
		List<Specs>splist=sm.selectByExample(se1);
		if(listSpecs.get(0)!="") {
			for(int i=0;i<listSpecs.size();i++) {
				BigDecimal bigDecimal2 =new BigDecimal(listPrice.get(i));
				sp.setProduct(id);
				sp.setName(listName);
				sp.setProductNum(Integer.parseInt(listNum.get(i)));
				sp.setProductPrice(bigDecimal2);
				SpecsExample se =new SpecsExample();
				se.createCriteria().andProductEqualTo(id);

				if(splist.size()==0) {
					
					ok=sm.insertSelective(sp);
				}else {
					ok=sm.updateByExampleSelective(sp, se);
				}
				
			}
		}
		
		if(ok==0) {
			return new Result(ok,"修改失败2");
		}
		
		
		
		
		String path= uploadDir[0].substring("file:/".length());
		String fileName="";
		/**
		 * 图片表修改
		 */
		Image image =new Image();
		if(file.length!=0) {
			ImageExample ie1=new ImageExample();
			ie1.createCriteria().andProductEqualTo(id);
			List<Image>imlist= im.selectByExample(ie1);
			for(int i=0;i<file.length;i++) {
				String productFileName=file[i].getOriginalFilename();
				String suffix = productFileName.substring(productFileName.lastIndexOf('.'));
				String addFileName=String.valueOf(System.currentTimeMillis()).substring(6);
				fileName = "business/product/"+addFileName+suffix;
				
				//判断文件类型是否正确
				String contentType = file[i].getContentType();
				String result1="";
				if (contentType.equals("image/pjpeg")
						|| contentType.equals("image/jpeg")) {
					// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
				} else if (contentType.equals("image/png")
						|| contentType.equals("image/x-png")) {
					// IE6上传的png图片的headimageContentType是"image/x-png"
				} else if (contentType.equals("image/jfif")) {
				}else if (contentType.equals("image/gif")) {
				}else if (contentType.equals("image/bmp")) {
				} else {
					return new Result(0, "文件类型错误");
				}
				
				
				File diskFile=new File(path+fileName);
				File diskFile1=new File("../"+fileName);
				if (!diskFile.exists()) { // 如果路径不存在，创建
					diskFile.mkdirs();
				}
				System.out.println("diskFile:"+diskFile);
				file[i].transferTo(diskFile);
				image.setProduct(id);
				image.setUrl(diskFile1.toString());
				//image.setBusiness(business.getId());
				/**
				 * 默认图片状态为 2 已启用
				 */
				image.setState(2);
				
//				ImageExample ie =new ImageExample();
//				ie.createCriteria().andProductEqualTo(id);
				
			
				ok=im.insertSelective(image);
				
				
			}
		}
		
		if(ok>0) {
			return new Result(1,"修改商品成功");
		}else {
			return new Result(0,"修改失败");
		}
		
	} 
}
